package cn.coco.jf.fw.admin.sys.controller.ssoAuth;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.coco.jf.fw.core.db.SysMenuTbl;
import cn.coco.jf.fw.core.db.SysThirdUserTbl;
import cn.coco.jf.fw.core.db.SysUserTbl;
import cn.coco.jf.fw.admin.config.consts.SysConfigConst;
import cn.coco.jf.fw.admin.config.consts.SysConsts;
import cn.coco.jf.fw.admin.controller.FwBaseController;
import cn.coco.jf.fw.admin.model.JkUser;
import cn.coco.jf.fw.admin.sys.dao.SysDao;
import cn.coco.jf.fw.admin.sys.dao.login.LoginDao;
import cn.exlu.coco.core.exception.CoCoException;
import cn.exlu.coco.core.utils.CipherUtil;
import cn.exlu.coco.core.utils.HttpUtil;
import cn.exlu.coco.core.utils.StringUtil;

@Clear
public class SSOAuthController extends FwBaseController {
	private static Logger _LOG = Logger.getLogger(SSOAuthController.class);
	
	public void redirectSSO() {
		String url = SysConfigConst.SYSTEM_SSO_URL_LOGIN + ( SysConfigConst.SYSTEM_SSO_URL_LOGIN.indexOf("?") > 0 ?"&" : "?" ) + "appId=" + SysConfigConst.SYSTEM_SSO_APPID + "&authType=" + SysConfigConst.SYSTEM_SSO_AUTHTYPE;
		this.redirect(url, true);
	}

	@Before(Tx.class)
	public void checkAuth() {
    	String authCode = this.getPara("authCode");
    	String appUrl = this.getPara("appUrl");
    	
    	// 获取授权用户信息
    	Map<String, String> reqMap = new HashMap<String, String>();
    	reqMap.put("appId", SysConfigConst.SYSTEM_SSO_APPID);
    	reqMap.put("authCode", authCode);
    	
    	StringBuilder sb = new StringBuilder();
        sb.append("appId=").append(SysConfigConst.SYSTEM_SSO_APPID)
        .append("authCode=").append(authCode)
        .append("appKey=").append(SysConfigConst.SYSTEM_SSO_APPKEY);
        String signature = CipherUtil.encodeBySha256(sb.toString());
        
        reqMap.put("signature", signature);
        
    	try {
			String respMsg = HttpUtil.get(SysConfigConst.SYSTEM_SSO_URL_AUTHINFO,reqMap);
			
			JSONObject respJson = JSONObject.parseObject(respMsg);
			int resp_code = respJson.getIntValue("code");
			if(resp_code != 200) {
				this.renderError(SysConsts.RENDER_ERR_601_NO_AUTH);
			}
			
			// 获取用户CODE
			JSONObject respJson_obj = respJson.getJSONObject("data");
			String userCodeThird = respJson_obj.getString("userCode");
			String userName = respJson_obj.getString("userName");
			
			// 查询该账号是否已经存在
			SysThirdUserTbl sysThirdUserTbl = SysThirdUserTbl.dao.findByIds(SysConfigConst.SYSTEM_SSO_AUTHTYPE, userCodeThird);
			
			String userCode = SysConfigConst.SYSTEM_SSO_AUTHTYPE + "_" + userCodeThird;
			if(sysThirdUserTbl == null) {
				
				// 当前用户不存在的场合
				// 新建用户并赋予默认权限
				SysUserTbl sysUserTbl = new SysUserTbl();
				sysUserTbl.setUserCode(userCode);
				sysUserTbl.setUserName(userName);
				sysUserTbl.setRoleId(SysConfigConst.SYSTEM_USER_ROLEID_DEFAULT);
				sysUserTbl.setCreateUser(SysConfigConst.SYSTEM_USER_CODE);
		        Date date = new Date();
		        sysUserTbl.setCreateDateTime(date);
		        sysUserTbl.setUpdateUser(SysConfigConst.SYSTEM_USER_CODE);
		        sysUserTbl.setUpdateDateTime(date);
				sysUserTbl.setDelFlg(SysConsts.DEL_FLG_NORMAL);
				sysUserTbl.setUserCodeThird(userCode);

				sysUserTbl.save();
				
				sysThirdUserTbl = new SysThirdUserTbl();
				sysThirdUserTbl.setAuthType(SysConfigConst.SYSTEM_SSO_AUTHTYPE);
				sysThirdUserTbl.setUserCodeThird(userCodeThird);
				sysThirdUserTbl.setUserNameThird(userName);
				sysThirdUserTbl.setUserCode(userCode);
				sysThirdUserTbl.setCreateDateTime(date);
				sysThirdUserTbl.setUpdateUser(SysConfigConst.SYSTEM_USER_CODE);
				sysThirdUserTbl.setUpdateDateTime(date);
				
				sysThirdUserTbl.save();
				
			}
			
			JkUser jkUser = LoginDao.selectNormalByKey(userCode);
			
			// 更新登录名
			jkUser.setUserName(userName);
			
			List<SysMenuTbl> sysMenuTblList = SysDao.querySysMenuTblListByRoleId(jkUser.getRoleId());
      		 List<String> menuUrlList = new ArrayList<String>();
      		 String menuUrl = "";
      		 for(SysMenuTbl item:sysMenuTblList){
      		     menuUrl = item.getMenuUrl();
      		     if(!StringUtil.isNullOrEmpty(menuUrl)){
                     String[] menuUrls = menuUrl.split(",");
                     for(String url :menuUrls){
                         menuUrlList.add(url);
                     }
                     
                 }

      		 }

      		 // 检索用户菜单
      		 jkUser.setMenus(menuUrlList);
      		 
      		 jkUser.getMenus().add("/");

      		 setSessionAttr("jkUser", jkUser);
			
			
    	} catch (CoCoException e) {
			_LOG.error("系统异常：", e);
			this.renderError(500);
			return;
		}
		
		this.redirect("/");
    	
	}

    
    
    
    
}
